package com.sms.gui.actions;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import com.sms.util.ResourcesHandler;

public class SetDestinatarioAction extends AbstractAction {

    private static final long serialVersionUID = 1L;
    private JLabel destField;

    public SetDestinatarioAction(JLabel destField2) {
        super();
        destField = destField2;
        putValue(AbstractAction.NAME, "Seleziona destinatario");
        putValue(AbstractAction.SMALL_ICON, ResourcesHandler.WEB_IMG);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String dest = JOptionPane.showInputDialog(null, "Destinatario:",
                "Destinatario", JOptionPane.INFORMATION_MESSAGE);
        if (dest != null && isRegularNumber(dest)) {
            putValue(AbstractAction.NAME, "Cambia destinatario");
            destField.setText(dest);
        } else if (dest == null) {
            putValue(AbstractAction.NAME, "Seleziona destinatario");
        } else if (!isRegularNumber(dest)) {
            JOptionPane.showMessageDialog(null,
                    "Il numero inserito non e' valido", "Errore",
                    JOptionPane.ERROR_MESSAGE);
            putValue(AbstractAction.NAME, "Seleziona destinatario");
        }
    }

    private boolean isRegularNumber(String input) {
        if (input.length() < 10)
            return false;
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (i == 0 && c != '3')
                return false;
            if (i > 0 && (c < '0' || c > '9'))
                return false;
        }
        return true;
    }
}